#!/bin/sh
# $Id: $

c200_var_hsize=1000
c200_var_hfile=/share/.history

c200_fn_prompt() {
    echo 
    /bin/echo -n "$USER@`hostname` [$PWD] > "
}

c200_fn_lasthist() {
    if [ -f "$c200_var_hfile" ] ; then
        awk 'END { print $1; }' "$c200_var_hfile"
    else
        echo 0
    fi
}

c200_fn_wcl() {
    if [ -f "$1" ] ; then
        awk 'END { print NR; }' "$@" 
    else
        echo 0
    fi
}

c200_fn_trimhist() {
    if [ $(( `c200_fn_wcl $c200_var_hfile` - $c200_var_hsize -1 )) -gt 0 ] ; then
        sed -i "1,$s d" $c200_var_hfile >/dev/null 2>&1
    fi
}

c200_var_tab="	"

c200_fn_record() {
    if [ -n "$1" ] ; then
        histno=$((`c200_fn_lasthist` + 1 ))
        if [ -f "$c200_var_hfile" ] ; then
            if fgrep -q "$c200_var_tab$1$c200_var_tab" $c200_var_hfile ; then
                return
            fi
        fi
        echo "$histno$c200_var_tab$1$c200_var_tab" >> $c200_var_hfile
        c200_fn_trimhist
    fi
}

c200_fn_showhist() {
    
    sed "s/$c200_var_tab/ /" $c200_var_hfile 2>/dev/null || echo "No history"
    echo
}

c200_fn_runhist() {
    c200_var_histno="${1#!}"
    c200_var_line=`sed -rn "/^$c200_var_histno$c200_var_tab/ {s/^[0-9]+$c200_var_tab//;s/$c200_var_tab\$//;p}" $c200_var_hfile`
    echo ">> $c200_var_line <<"
    c200_fn_record "$c200_var_line"
    eval "$c200_var_line"
}
    
c200_fn_helphist() {
cat <<HERE
h      - history
!12     - run command 12 in history
!h     - delete history
s/a/b/ - sed on last command
q      - quit
HERE
}

 
c200_fn_helphist
while true ; do

    c200_fn_prompt

    c200_var_lastline="$c200_var_line"

    read c200_var_line 
    
    case "$c200_var_line" in
        *!!*) c200_var_line=`echo "$c200_var_line" | sed "s/!!/$c200_var_lastline/g"`
            echo "[ $c200_var_line ]"
            ;;
    esac
    case "$c200_var_line" in
    exit|q)
        break ;;
    h)
        c200_fn_showhist ;;
    !h)
        rm -f "$c200_var_hfile"
        ;;
    ![0-9]*)
        c200_fn_runhist "$c200_var_line" ;;
    s/*)
        c200_var_line=`echo "$c200_var_lastline" | sed -r "$c200_var_line"`
        echo ">> $c200_var_line <<"
        c200_fn_record "$c200_var_line"
        eval "$c200_var_line"
        ;;
        
    \?) c200_fn_helphist;;

    *)
        c200_fn_record "$c200_var_line"
        eval "$c200_var_line"
        ;;
    esac
done
